<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Validate;

class Api extends Controller
{
    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        apiReturn(1, '获取数据成功', $user_data);
    }

    /**
     * 微信登录
     * */
    public function wxLogin()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, 'code缺失');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $user_data = json_decode(file_get_contents($url));

        $openid = $user_data->openid;

        $info = Db::name('user')->where(['openid' => $openid])->find();
        if ($info) {
            $return_data = [
                'user_id' => $info['id'],
                'openid' => $info['openid']
            ];
            apiReturn(1, '登录成功', $return_data);
        } else {
            $data = [
                'openid' => $openid,
                'create_time' => time()
            ];

            $user_id = Db::name('user')->insertGetId($data);
            if ($user_id) {
                $return_data = [
                    'user_id' => $user_id,
                    'openid' => $openid
                ];
                apiReturn(1, '登录成功', $return_data);
            } else {
                apiReturn(2, '登录失败');
            }
        }

    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $code = $input['code'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = get_access_token('xcx_access_token.json', 2);
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                $count = Db::name('user')->where(['mobile' => $mobile])->count();
                if ($count > 0) apiReturn(2, '手机号码已存在');

                $update_user_data['mobile'] = $mobile;

                $user_info = Db::name('user')->field('level,up_user_id')->where(['id' => $user_id])->find();
                if ($user_info['level'] == 1 && $user_info['up_user_id'] > 0) {
                    $update_user_data['level'] = 2;

                    // 某个用户的级别变更需要将其所有上级都加入到用户升级的任务计划
                    addAllUpUserToUpPlan($user_id);
                }

                Db::name('user')->where(['id' => $user_id])->update($update_user_data);

                apiReturn(1, '获取数据成功', $mobile);
            } else {
                file_put_contents(RUNTIME_PATH . 'mobileErrGetMobile.txt', '手机号不存在===>' . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            file_put_contents(RUNTIME_PATH . 'ApiErrGetMobile.txt', '时间：' . date('Y-m-d H:i:s') . '，用户ID：' . $user_id . ' ===> 错误码：' . $result['errcode'] . '；错误信息：' . $result['errmsg'] . '；code：' . $code . PHP_EOL, FILE_APPEND);
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 获取门店信息
     * */
    public function getShopInfo()
    {
        $info = Db::name('shop')->where(['id' => 1])->find();
        if ($info) {
            $info['full_send_price'] = (int) C('FULL_SEND_PRICE');
            $info['img_path'] = getPicture($info['img']);
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '门店信息缺失');
        }
    }

    /**
     * 动态列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('article')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['imgs_arr'] = doImgs($v['imgs']);
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 动态详情
     * */
    public function articleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '动态ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time']);
            $info['content'] = doEditorContent($info['content']);
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '动态不存在或已删除');
        }
    }


    /**
     * 商品分类
     * */
    public function goodsTypeList()
    {
        $list = Db::name('goods_type')->field('id,name')->order('sort asc')->select();

        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $type_id = $input['type_id'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['upper'] = 1;

        if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
        if ($type_id) $where['type_id'] = $type_id;

        $goods_list = Db::name('goods')->field('id,name,img,price,imgs,sales_count')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $v['img'] = getPicture($v['img']);
                $v['imgs'] = doImgs($v['imgs']);
                $v['buy_count'] = 0;
            }
            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 确认订单页面 => 收货地址 && 门店信息 && 自提时间数据
     * */
    public function confirmOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $address_info = Db::name('address')->where(['user_id' => $user_id])->find();
        $shop_info = Db::name('shop')->where(['id' => 1])->find();


        $today_section = C('TODAY_SECTION');
        $later_section = C('LATER_SECTION');
        $time_arr = [['今天', date("m月d日", strtotime("+1 day")), date("m月d日", strtotime("+2 day"))], $today_section];

        $data = [
            'address_info' => $address_info ? : [],
            'shop_info' => $shop_info,
            'multiArray' => $time_arr,
            'arrColumn0' => $today_section,
            'arrColumn1' => $later_section,
            'arrColumn2' => $later_section
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 获取备注快捷短语
     * */
    public function getFastRemark()
    {
        $data = ['挂门把手上', '放门口', '放门卫', '放前台桌上', '请电话联系我', '不要敲门', '请清洗干净', '请挑新鲜点不要有坏果', '挑甜一点大一点', '挑熟一点的', '分量给足哦'];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 创建待支付订单
     * */
    public function createWaitPayOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $car_list = $input['car_list'] ? json_decode($input['car_list'], true) : [];
        $type = $input['type'];// 1：外送，2：自提
        $get_username = $input['get_username'];
        $get_mobile = $input['get_mobile'];
        $get_address = $input['get_address'];
        $zt_time = $input['zt_time'];
        $zt_mobile = $input['zt_mobile'];
        $remark = $input['remark'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_list)) apiReturn(2, '请选购商品');
        if ($type == 1) {
            // 外送
            if (empty($get_username) || empty($get_mobile) || empty($get_address)) apiReturn(2, '请完善收货地址');
        } elseif ($type == 2) {
            // 自提
            if (empty($zt_time)) apiReturn(2, '请选择自提时间');
            if (empty($zt_mobile)) apiReturn(2, '请输入自提联系方式');
        }

        Db::startTrans();
        try {
            $time = time();
            $sn = date('ymdHi') . rand(100000, 999999);

            $all_price = 0;
            $vice_order_data = [];
            foreach ($car_list as &$v) {
                $all_price += $v['count'] * $v['price'];
                $vice_order_data[] = [
                    'goods_id' => $v['id'],
                    'img' => $v['img'],
                    'name' => $v['name'],
                    'price' => $v['price'],
                    'count' => $v['count'],
                    'create_time' => $time
                ];
            }

            $order_data = [
                'user_id' => $user_id,
                'order_sn' => 'SN' . $sn,
                'pay_order_sn' => 'PAY' . $sn,
                'all_price' => $all_price,
                'pay_price' => $all_price,
                'type' => $type,
                'remark' => $remark,
                'create_time' => $time
            ];

            if ($type == 1) {
                $order_data['get_username'] = $get_username;
                $order_data['get_mobile'] = $get_mobile;
                $order_data['get_address'] = $get_address;
            } elseif ($type == 2) {
                $order_data['zt_time'] = $zt_time;
                $order_data['zt_mobile'] = $zt_mobile;
            }

            $order_id = Db::name('order')->insertGetId($order_data);

            $push_arr = ['order_id' => $order_id];

            // 给$vice_order_data的每一项追加order_id
            array_walk($vice_order_data, function (&$value, $key, $arr) {
                $value = array_merge($value, $arr);
            },         $push_arr);

            Db::name('vice_order')->insertAll($vice_order_data);

            if ($type == 1) {
                $count = Db::name('address')->where(['user_id' => $user_id])->count();
                if ($count) {
                    $address_data = [
                        'user_id' => $user_id,
                        'username' => $get_username,
                        'mobile' => $get_mobile,
                        'address' => $get_address,
                        'update_time' => $time
                    ];
                    Db::name('address')->where(['user_id' => $user_id])->update($address_data);
                } else {
                    $address_data = [
                        'user_id' => $user_id,
                        'username' => $get_username,
                        'mobile' => $get_mobile,
                        'address' => $get_address,
                        'create_time' => $time
                    ];
                    Db::name('address')->insert($address_data);
                }
            }

            Loader::import('wxsdk\wxPay', EXTEND_PATH);

            $obj = new \wxPay();

            $openid = Db::name('user')->where(['id' => $user_id])->value('openid');
            if(empty($openid)){
                Db::rollback();
                apiReturn(2, '支付失败');
            }

            //调用示例（最后两个参数为可选参数）
            $pay_data = $obj->jsApi($openid, 0.01, 'PAY' . $sn, '商品支付', getHost() . '/Index/Notify/notice');

            $return_data = [
                'pay_data' => $pay_data,
            ];

            Db::commit();
            apiReturn(1, '获取数据成功', $return_data);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '待支付订单生成失败');
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        switch ($status) {
            case 1:
                $where['status'] = 1;
                break;
            case 2:
                $where['status'] = 2;
                break;
            case 3:
                $where['status'] = 3;
                break;
            case 4:
                $where['status'] = 4;
                break;
            case 5:
                $where['status'] = ['IN', [5, 6, 7]];
                break;
        }

        $list = Db::name('order')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_desc'] = doOrderStatus($v['status'], $v['type']);
                $v['create_time'] = timeFormat($v['create_time']);

                $goods_list = Db::name('vice_order')->where(['order_id' => $v['id']])->select();
                if ($goods_list) {
                    foreach ($goods_list as &$val) {
                        $val['img'] = getPicture($val['img']);
                    }
                    $v['goods_list'] = $goods_list;
                }
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 申请售后
     * */
    public function applyAfter()
    {
        $input = Request()->param();

        $id = $input['id'];
        $after_reason = $input['after_reason'];
        $after_imgs = $input['after_imgs'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (empty($after_reason)) apiReturn(2, '请填写申请理由');

        $data = [
            'after_reason' => $after_reason,
            'after_imgs' => $after_imgs,
            'status' => 5,
            'update_time' => time()
        ];
        $res = Db::name('order')->where(['id' => $id])->update($data);
        if ($res) {
            apiReturn(1, '申请提交成功');
        } else {
            apiReturn(2, '申请提交失败');
        }
    }

    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();
        if ($info) {
            $info['status_desc'] = doOrderStatus($info['status'], $info['type']);
            $info['pay_time'] = timeFormat($info['pay_time']);

            $shop_info = Db::name('shop')->where(['id' => 1])->find();
            $info['shop_info'] = $shop_info;

            $goods_list = Db::name('vice_order')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = getPicture($val['img']);
                }
                $info['goods_list'] = $goods_list;
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 删除订单
     * */
    public function delOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $count = Db::name('order')->where(['id' => $id])->count();
        if ($count) {
            $res = Db::name('order')->where(['id' => $id])->update(['is_del' => 1, 'update_time' => time()]);
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 确认收货
     * */
    public function confirmGet()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $count = Db::name('order')->where(['id' => $id])->count();
        if ($count) {
            Db::startTrans();
            try {
                Db::name('order')->where(['id' => $id])->update(['status' => 4, 'update_time' => time()]);

                $vice_order_list = Db::name('vice_order')->where(['order_id' => $id])->select();
                if ($vice_order_list) {
                    foreach ($vice_order_list as &$v) {
                        Db::name('goods')->where(['id' => $v['goods_id']])->setInc('sales_count', $v['count']);
                    }
                }

                Db::commit();
                apiReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '操作失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }


}
